package com.future.hedongjun.mine.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.future.baselib.activity.BaseActivity;
import com.future.baselib.entity.BaseResponse;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.entity.MessageEvent;
import com.future.baselib.http.HttpRequest;
import com.future.baselib.utils.EventBusUtil;
import com.future.baselib.utils.PatternUtils;
import com.future.hedongjun.R;
import com.future.hedongjun.common.Contant;
import com.future.hedongjun.common.MyApp;
import com.future.hedongjun.mine.bean.response.UserInfoResponse;

import butterknife.BindColor;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RegisterActivity extends BaseActivity {

    @BindView(R.id.et_mobile)
    EditText etPhone;
    @BindView(R.id.btn_getCode)
    Button btnGetCode;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.et_pwd)
    EditText etPassword;
    @BindView(R.id.et_pwd_again)
    EditText etPasswordAgain;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_protocol)
    TextView tvProtocol;
    @BindColor(R.color.colorPrimary)
    int titleColor;
    @BindView(R.id.tv_binding_phone)
    TextView tvBindingPhone;
    @BindView(R.id.layout_protocol)
    LinearLayout layoutProtocol;
    private int type = 1;
    private String openid;
    private String platKey;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        if (type == 1) {
            setTitle("注册");
            btnLogin.setText("注册");
        } else if (type == 2) {
            setTitle("忘记密码");
            btnLogin.setText("确认");
            layoutProtocol.setVisibility(View.GONE);
        } else if (type == 3) {
            setTitle("安全绑定");
            tvBindingPhone.setVisibility(View.VISIBLE);
            btnLogin.setText("安全绑定");
        }
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        if (extras != null) {
            type = extras.getInt("type", 1);
            if (type == 3) {
                openid = extras.getString("token");
                platKey = extras.getString("platKey");
            }
        }
    }

    @OnClick({R.id.btn_getCode, R.id.btn_login, R.id.tv_protocol})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_getCode:
                getCode();
                break;
            case R.id.btn_login:
                register();
                break;
            case R.id.tv_protocol:
                startActivity(UserProtocolActivity.class);
                break;
        }
    }

    @SuppressWarnings("unchecked")
    private void register() {
        final String phone = etPhone.getText().toString().trim();
        String code = etCode.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String passwordAgain = etPasswordAgain.getText().toString().trim();

        if (!PatternUtils.mobilePattern(toast, phone)) {
            return;
        }

        if (TextUtils.isEmpty(code)) {
            toast("请输入验证码");
            return;
        }
        if (code.length() < 4) {
            toast("请输入正确验证码");
            return;
        }

        if (!PatternUtils.passwordPattern(toast, password)) {
            return;
        }
        if (TextUtils.isEmpty(passwordAgain)) {
            toast("确认密码不能为空");
            return;
        }
        if (!TextUtils.equals(password, passwordAgain)) {
            toast("两次密码输入不一致");
            return;
        }

        HttpRequest request = new HttpRequest<UserInfoResponse>();
        String apiCode = "";
        switch (type) {
            case 1:
                apiCode = "/api/User/register";
                request.addParam("password", password);
//                        .addParam("two_pwd", passwordAgain);
                break;
            case 2:
                apiCode = "/api/User/resetpwd";
                request.addParam("newpassword", password);
                break;
            case 3:
                apiCode = "/api/User/bindmobile";
                request.addParam("openid", openid)
                        .addParam("platform",platKey)
                        .addParam("password",password);
                break;
        }

        request.with(this)
                .setPath(apiCode)
                .addParam("mobile", phone)
                .addParam("captcha", code)
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        switch (type) {
                            case 1:
                                MyApp.getInstance().setUserInfo(((UserInfoResponse) response).userInfo);
                                EventBusUtil.sendEvent(new MessageEvent(Contant.EVENT_CODE_LOGIN));
                                setResult(0x123);
                                finish();
                                break;
                            case 2:
                                finish();
                                break;
                            case 3:
                                MyApp.getInstance().setUserInfo(((UserInfoResponse) response).userInfo);
                                EventBusUtil.sendEvent(new MessageEvent(Contant.EVENT_CODE_LOGIN));
                                setResult(0x123);
                                finish();
                                break;
                        }

                    }
                });


        request.start(new UserInfoResponse());
    }

    @SuppressWarnings("unchecked")
    private void getCode() {
        String mobile = etPhone.getText().toString().trim();
        if (!PatternUtils.mobilePattern(toast, mobile)) {
            return;
        }

        String event = "";
        if (type == 1) {
            event = "register";
        } else if(type == 2){
            event = "resetpwd";
        }else if(type == 3){
            event = "mobilelogin";
        }

        btnGetCode.setClickable(false);
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setPath("/api/Sms/send")
                .addParam("event", event)
                .addParam("mobile", mobile)
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        new Thread(runnable).start();
                    }
                })
                .addFailListener(new HttpRequest.OnNetworkFail() {
                    @Override
                    public void onFail(String message) {
                        btnGetCode.setClickable(true);
                        toast(message);
                    }
                }).start(new DefaultResponse());
    }


    //验证码发送倒计时
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    btnGetCode.setClickable(false);
                }
            });
            for (int i = 60; i > 0; i--) {
                final int finalI = i;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btnGetCode.setText("重新获取(" + finalI + ")");
                    }
                });
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    btnGetCode.setClickable(true);
                    btnGetCode.setText("重新获取");
                }
            });
        }
    };
}
